package com.freesaas.merchant.service;

import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fast.common.exception.FastException;
import com.fast.common.util.BeanUtils;
import com.fast.common.util.DateUtils;
import com.freesaas.merchant.dao.PayinOrderDao;
import com.freesaas.merchant.entity.PayinOrder;
import com.freesaas.merchant.util.PubDataUtil;
import com.freesaas.merchant.vo.P00201Request;
import com.payment.channel.api.PayinService;
import com.payment.channel.service.PayinServiceImpl;
import com.payment.channel.vo.WechatPayCallbackRequest;

@Service
public class CreateOrderService {

	private Logger logger = LoggerFactory.getLogger(CreateOrderService.class);

	@Autowired
	private PayinOrderDao payInOrderDao;

	private PayinService payinService = new PayinServiceImpl();

	/**
	 * 支付交易
	 * 
	 * @param request
	 * @param remoteIp
	 * @param busTyp
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> P00201(P00201Request request, String remoteIp, String busTyp) throws Exception {
		PayinOrder obj = new PayinOrder();
		obj.setOrdNo(PubDataUtil.getJrnNo());
		obj.setAplAmt(NumberUtils.createBigDecimal(request.getTxnAmt()));
		obj.setMercId(request.getMercId());
		obj.setMercOrdDate(DateUtils.getCurrentDate());
		obj.setMercOrdNo(PubDataUtil.getJrnNo());
		obj.setOrdDt(DateUtils.getCurrentDate());
		obj.setOrdTm(DateUtils.getCurrentTime());
		obj.setOrdSts("N");
		obj.setRemoteIp(remoteIp);
		obj.setSysCnl("11");
		obj.setBusTyp(busTyp);// 微信
		obj.setIsChk("00");
		obj.setIsSettle("00");
		obj.setUsrSign(request.getOpenId());
		obj.setNotifyUrl("http://merchant.freesaas.cn/channel/P00301");
		int result = payInOrderDao.save(obj);
		if (result <= 0) {
			throw new FastException("DB0001");
		}
		Map<String, Object> req = BeanUtils.toFlatMap(obj);
		req.put("openId", request.getOpenId());
		req.put("body", "订单-" + obj.getMercOrdNo());
		Map<String, String> retmap = payinService.payin(req);
		return retmap;
	}

	/**
	 * 回调更新订单状态
	 * 
	 * @param responseString
	 * @throws Exception
	 */
	public void P00202(String responseString) throws Exception {
		WechatPayCallbackRequest retmap = payinService.callback(responseString);
		logger.info("返回的内容：{}", retmap);
		PayinOrder obj = new PayinOrder();
		obj.setOrdNo(retmap.getOutTradeNo());
		obj.setCnlOrdNo(retmap.getTransactionId());
		obj.setRspCode(retmap.getReturnCode());
		obj.setRspMsg(retmap.getReturnMsg());
		Map<String, Object> param = BeanUtils.toFlatMap(obj);
		param.put("oldOrdSts", "N");
		int result = payInOrderDao.updateByOrdNoWithStatus(param);
		if (result <= 0) {
			throw new FastException("DB0001");
		}
	}
}
